package net.tbao.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.tbao.common.utils.HttpUtils;
import net.tbao.member.dao.MemberLevelDao;
import net.tbao.member.entity.MemberLevelEntity;
import net.tbao.member.exception.PhoneExsitException;
import net.tbao.member.exception.UsernameExsitException;
import net.tbao.member.vo.MemberLoginVo;
import net.tbao.member.vo.MemberRegistVo;
import net.tbao.member.vo.PersonalVo;
import net.tbao.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.tbao.common.utils.PageUtils;
import net.tbao.common.utils.Query;

import net.tbao.member.dao.MemberDao;
import net.tbao.member.entity.MemberEntity;
import net.tbao.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //设置会员默认等级
       MemberLevelEntity levelEntity= memberLevelDao.getDefaultLevel();
       entity.setLevelId(levelEntity.getId());

       //检查用户名和手机号是否唯一
        checkPhonelUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setCreateTime(new Date());

        //密码进行加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        memberDao.insert(entity);
    }

    /**
     * 检查手机号是否唯一
     * @param phone
     * @return
     */
    @Override
    public void checkPhonelUnique(String phone)throws PhoneExsitException {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile>0){
            throw new PhoneExsitException();
        }
    }

    /**
     *检查用户名是否唯一
     * @param username
     * @return
     */
    @Override
    public void checkUsernameUnique(String username)throws UsernameExsitException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new UsernameExsitException();
        }

    }


    /**
     * 用户登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {

        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLogincct())
                .or().eq("mobile", vo.getLogincct()));
        if (memberEntity == null) {
            return null;
        } else {
            String passwordDB = memberEntity.getPassword(); // 获取数据库中加密的密码
            // spring家加密机制 让提交的密码与数据库的密文密码进行匹配
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(vo.getPassword(), passwordDB);
            if (matches) { // 匹配成功
                return memberEntity;
            } else {
                return null;
            }
        }

    }

    /**
     * 社交登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocialUserVo vo) throws Exception {
        String uid = vo.getUid();
        //判断当前社交用户是否登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity count = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(count!=null){
            //用户注册过
            MemberEntity updated=new MemberEntity();
            updated.setId(count.getId());
            updated.setAccessToken(vo.getAccess_token());
            updated.setExpiresIn(vo.getExpires_in());
            count.setAccessToken(vo.getAccess_token());
            count.setExpiresIn(vo.getExpires_in());

            memberDao.updateById(updated);
            return count;
        }else {
            //没有查到当前社交用户对应的记录，进行注册
            MemberEntity regist=new MemberEntity();
            try {  //查出社交用户资料
                Map<String, String> query = new HashMap<>();
                query.put("access_token", vo.getAccess_token());
                query.put("uid", vo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    //头像
                    String imageUrl = jsonObject.getString("avatar_large");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                    regist.setHeader(imageUrl);
                }

            }catch (Exception e) {
                e.printStackTrace();
            }
                regist.setSocialUid(vo.getUid());
                regist.setAccessToken(vo.getAccess_token());
                regist.setExpiresIn(vo.getExpires_in());
                memberDao.insert(regist);
                return regist;
        }
    }

    /**
     * 用户登录查询个人中心
     * @param vo
     * @return
     */
    //TODO 查询个人资料
    @Override
    public MemberEntity queryByPersonal(PersonalVo vo) {

        return null;
    }

}